package org.acmclass.fatworm.test.result;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

import org.acmclass.fatworm.test.FatTestException;

public class ResultValidator extends AnswerGenerator {

	private String answerFile, resultFile;
	private String compare_result = null;

	public static final String OK = "Correct";
	public static final String WA = "Wrong Answer";

	public ResultValidator(String answerFile, String resultFile)
			throws FatTestException {
		super(resultFile);
		this.answerFile = answerFile;
		this.resultFile = resultFile;
	}

	@Override
	public void close() throws FatTestException {
		super.close();
		try {
			compareFiles(answerFile, resultFile);
		} catch (IOException e) {
			throw new FatTestException("error while comparing files:"
					+ answerFile + " and " + resultFile, e);
		}
	}

	private void compareFiles(String answer, String result) throws IOException {
		BufferedReader reader0 = new BufferedReader(new FileReader(answer));
		BufferedReader reader1 = new BufferedReader(new FileReader(result));
		compare_result = WA;

		try {
			String line0 = reader0.readLine(), line1 = reader1.readLine();
			while (line0 != null && line1 != null) {
				if (!line0.equals(line1)) {
					return;
				}

				line0 = reader0.readLine();
				line1 = reader1.readLine();
			}
			if (line0 != null || line1 != null) {
				return;
			}

			compare_result = OK;
		} finally {
			if (reader0 != null)
				reader0.close();
			if (reader1 != null)
				reader1.close();
		}
	}

	@Override
	public String getResult() {
		return compare_result;
	}

}
